from qcloud_cos import CosConfig, CosS3Client, CosServiceError
import os
import logging

class TencentCOS:
    def __init__(self, secret_id=None, secret_key=None, region='ap-guangzhou'):
        """
        初始化COS客户端
        :param secret_id: 从环境变量COS_SECRET_ID自动读取
        :param secret_key: 从环境变量COS_SECRET_KEY自动读取
        """
        # self.secret_id = secret_id or os.getenv('COS_SECRET_ID')
        # self.secret_key = secret_key or os.getenv('COS_SECRET_KEY')
        self.secret_id = "AKaqulOo0yjGZdddddgbzA8sPjtqa"
        self.secret_key = "YtzsXyCDA80dddddffffePyJQ"
        self.region = region
        self.client = self._create_client()
        logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    def _create_client(self):
        config = CosConfig(
            Region=self.region,
            SecretId=self.secret_id,
            SecretKey=self.secret_key,
            Scheme='https'  # 强制HTTPS传输
        )
        return CosS3Client(config)

    def upload_file(self, bucket, local_path, cos_path, storage_class='STANDARD'):
        """智能上传（自动分块/续传)"""
        try:
            response = self.client.upload_file(
                Bucket=bucket,
                LocalFilePath=local_path,
                Key=cos_path,
                StorageClass=storage_class,  # 支持标准/低频/归档存储
                EnableMD5=True,  # 启用MD5校验
                PartSize=10,  # 单位MB
                MAXThread=20   # 并发线程数
            )
            logging.info(f"上传成功: {cos_path} ETag: {response['ETag']}")
            return response
        except CosServiceError as e:
            logging.error(f"上传失败: {e.get_error_code()}-{e.get_error_msg()}")
            raise

    def download_file(self, bucket, cos_path, local_path):
        """文件下载（含流式处理）"""
        response = self.client.get_object(
            Bucket=bucket,
            Key=cos_path,
        )
        response['Body'].get_stream_to_file(local_path)
        logging.info(f"下载完成: {local_path}")
        return local_path

    def delete_file(self, bucket, cos_path):
        """删除对象"""
        self.client.delete_object(Bucket=bucket, Key=cos_path)
        logging.info(f"已删除: {cos_path}")

    def list_buckets(self):
        """列出存储桶列表"""
        response = self.client.list_buckets()
        print(response['Buckets']['Bucket'])
        for bucket in response['Buckets']['Bucket']:
            # logging.info(f"存储桶: {bucket}")
            logging.info(f"存储桶: {bucket['Name']} 创建时间: {bucket['CreationDate']} 区域: {bucket['Location']}")

    def generate_presigned_url(self, bucket, cos_path, expire_sec=3600):
        """生成临时访问链接（适用于敏感数据分享）[6](@ref)"""
        return self.client.get_presigned_url(
            Method='GET',
            Bucket=bucket,
            Key=cos_path,
            Expired=expire_sec
        )
    
if __name__ == "__main__":
    # 初始化客户端（密钥通过环境变量注入）
    cos = TencentCOS(region='ap-chengdu')
    
    # 上传文件到存储桶
    bucket = 'test-1303833691'  # 格式: BucketName-APPID
    cos.upload_file(
        bucket=bucket,
        # local_path='/home/sietium/ceagle/code/cloud_backup/data/eosphorosai_dbgpt-openai_latest.tar',
        local_path='/home/sietium/ceagle/code/cloud_backup/data/test.txt',
        cos_path='data/test.txt',
        storage_class='STANDARD'  # 可选STANDARD|STANDARD_IA|ARCHIVE
    )
    
    cos.download_file(bucket, 'data/test.txt', '/home/sietium/ceagle/code/cloud_backup/data/test1.txt')
    # 生成临时访问链接
    url = cos.generate_presigned_url(bucket, 'data/test.txt')
    print("临时访问URL:", url)

    cos.list_buckets()